from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64


message = 'async'  # 消息原文

# 初始化乘积n长度为1024的RSA对象
rsa = RSA.generate(1024, Random.new().read)
# 生成私钥
private_key = rsa.exportKey()
# 生成公钥
public_key = rsa.publickey().exportKey()
# 打印私钥和公钥
print(private_key.decode('utf8'))
print(public_key.decode('utf8'))

# 将私钥和公钥存入对应名称的文件
with open('private.pem', 'wb') as f:
    f.write(private_key)

with open('public.pem', 'wb') as f:
    f.write(public_key)

with open('public.pem', 'r') as f:
    # 从文件中加载公钥
    pub = f.read()
    pubkey = RSA.importKey(pub)
    # 用公钥加密消息原文
    cipher = PKCS1_v1_5.new(pubkey)
    c = base64.b64encode(cipher.encrypt(message.encode('utf8'))).decode('utf8')

with open('private.pem', 'r') as f:
    # 从文件中加载私钥
    pri = f.read()
    prikey = RSA.importKey(pri)
    # 用私钥解密消息密文
    cipher = PKCS1_v1_5.new(prikey)
    m = cipher.decrypt(base64.b64decode(c), 'error').decode('utf8')

print('消息原文：%s\n消息密文:%s\n解密结果：%s' % (message, c, m))

# -----BEGIN RSA PRIVATE KEY-----
# MIICXgIBAAKBgQC6XsnrwP9N6Soid7DQWrNj8FGKAWCXNyO94vasR8vkmY5T6Sft
# wII5rj6Z5uwI8IbqV4tvc9u6DYWh/Sp2f16DUr0oTMR8POKGB1ESwQFhfXKr+qV/
# FR1Uxieyn+9k/2Qdx8l3TitBj739R6jWKAnL8U5vJLoia+J5AtuKuP+9fQIDAQAB
# AoGAKBVPcd5QOqJBjui1tVYwm3e6HcemjddM31/zZEHL0zaIgzkT/qFHEN9ONP0S
# umh65+dcxKODOEyEt36S9an2ukNhHzjmqmrbCx1Ag+xzh97HVmxWePL5ly67cMyo
# HxenD19hvietiYPGMjE6QnbUq2Hde2KytRsMbBgvU85iwKECQQDUls6m9l9ySttz
# kbk1BUrd8vIFsHGsh1lg/YJX/gMsvmxAWA15crjfidKZwzzLZ9MyQv4GooItV7r5
# LfibkCnhAkEA4G1haDN/MrLWYidC5jOTtGUu7CVc7rVDcW5cEXU4nfXrdVL9uzVn
# fvCN34xrYNEP7yUjAgoGrJX9vn9KCzDfHQJBAJ1gVvN7CAWQLQ1NH5KErHvKUiis
# Cjryp9QJV+jT/n2tKm4nwTHbH8k8Ok/iHKtn3Q0kUvGOdFgkziGRSq2+94ECQQCT
# Og5JnmbWao3LTDhN7g36rNowXn5ttons8toBNeYTcg2qJOyBEJK5qrNXsLWMiPms
# B6/EmbExLSCOBNEdME1dAkEAksIiSdDekI1Z0edzo+jGfBha/rGnfGD55Z38sjwf
# ECeuLe6m0wnaP6XPX6gUjkmervbBK3aj+w5lQzghYHeNAw==
# -----END RSA PRIVATE KEY-----
# -----BEGIN PUBLIC KEY-----
# MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6XsnrwP9N6Soid7DQWrNj8FGK
# AWCXNyO94vasR8vkmY5T6SftwII5rj6Z5uwI8IbqV4tvc9u6DYWh/Sp2f16DUr0o
# TMR8POKGB1ESwQFhfXKr+qV/FR1Uxieyn+9k/2Qdx8l3TitBj739R6jWKAnL8U5v
# JLoia+J5AtuKuP+9fQIDAQAB
# -----END PUBLIC KEY-----
# 消息原文：async
# 消息密文:gWjj58pzs93tmKkxGLIY2oN4yGpF8Xn1EGNmj8m2+H6Wwd++t3MTQ5IUqFjjcVhN05RTltudmbKxROoujhM40w2UZgsPDPiZe850Y5eP8ULzrzUv+HoXZO9wVSeyfCuTy+AnrpKihzL5wt4OI9X1Gvlgh6HXeXvTDNM4BXsUER8=
# 解密结果：async
